package com._58city.spark.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.spark.SparkConf;
import org.apache.spark.broadcast.Broadcast;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com._58city.spark.app.dao.CpcDisplayValue;
import com._58city.spark.app.ext.DaoUtil;
import com._58city.spark.app.ext.dto.DispCate;
import com._58city.spark.app.mr.MrKafkaCpcDisplay;

public class KafkaCpcDisplayStreaming {
	
	private static final int  batchInterval = 2000; //切片固定2s

	/**
	 * 运行参数3/4个：  kafka_topic 消费者ID(如ecdata_group) 接收线程数 [过滤IP]
	 * @param args
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		String kafka_topic = args[0]; //Kafka的topic，从运行参数传递进来
		String groupID = args[1];
		int numStreams = Integer.parseInt(args[2]); //开启几个Input DStream接收端
		
		String excludeIPStr = "";
		if(args.length >=4 ){
			excludeIPStr = args[3]; //过滤IP
		}
		AbstractApplicationContext context =  new ClassPathXmlApplicationContext("application-context.xml");
		DaoUtil.init(context); //初始化DAO，主要同步几个字典表
		CacheUtil.init(); //初始化Redis，主要用于统计后数据的存储
		
		Map<Long, DispCate> cate_map = CacheUtil.cateMap(); 
		
		SparkConf conf = new SparkConf()
				.set("spark.streaming.unpersist", "true") //Spark来计算哪些RDD需要持久化，这样有利于提高GC的表现。
				.set("spark.default.parallelism", "60")	//reduceByKeyAndWindow执行时启动的线程数，默认是8个
				.set("spark.yarn.driver.memoryOverhead", "1024") //Driver的堆外内存
				.set("spark.yarn.executor.memoryOverhead", "2048") //Executor的堆外内存
				.set("spark.storage.memoryFraction", "0.5") //RDD存储因子
				.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer") //Kryo序列化方式
				.set("spark.kryo.registrator", "com._58city.spark.app.kryo.Registrator"); //Kryo注册要序列化的类
		
		JavaStreamingContext jssc = new JavaStreamingContext(conf,new Duration(batchInterval)); //Spark的运行上下文 

		Broadcast<Map<Long, DispCate>> bc_cate_map = jssc.sc().broadcast(cate_map); //broadcast广播数据，通知各个Executor
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put(kafka_topic, 1); //每个Input DStream拉取的并发数
		/*
		 * 在多个Executor上开启Input DStreams
		 * 参数一：Spark的运行上下文
		 * 参数二：zk上注册的Kafka的目录
		 * 参数三：customer的group
		 * 参数四：Kafka Client的相关参数
		 * 参数五：Spark的存储形式，现在是只存一份
		 */
		Map<String, String> kafkaParams = new HashMap<String, String>();
		kafkaParams.put("group.id", groupID);
		kafkaParams.put("auto.offset.reset", "largest"); 
		//消息的最大大小
		kafkaParams.put("fetch.message.max.bytes", String.valueOf(20*1024*1024));
		kafkaParams.put("zookeeper.connect" ,"10.126.99.105:2181,10.126.99.196:2181,10.126.81.208:2181,10.126.100.144:2181,10.126.81.215:2181/58_kafka_cluster");
		
		List<JavaPairDStream<String, String>> kafkaStreams = new ArrayList<JavaPairDStream<String, String>>(numStreams);
		for (int i = 0; i < numStreams; i++) {
			 kafkaStreams.add(KafkaUtils.createStream(jssc,String.class,String.class,kafka.serializer.StringDecoder.class,kafka.serializer.StringDecoder.class, kafkaParams, map, StorageLevel.MEMORY_AND_DISK_SER()));
		}		
		/*
		 * 用于做map，reduce，foreach的操作类
		 * 参数一：要用于做Key的属性名
		 * 参数二：时间间隔
		 */
		MrKafkaCpcDisplay mr = new MrKafkaCpcDisplay(new String[]{"${platform}","${busiLine}"}, batchInterval,excludeIPStr);
		mr.setBc_cate_map(bc_cate_map);
		
		
		//MAP
		List<JavaPairDStream<String, CpcDisplayValue>> mapStreams = mr.mapPair(kafkaStreams);
		
		//将Stream全部聚合到第一个上
        JavaPairDStream<String, CpcDisplayValue> unionStream = null;
        if(mapStreams.size() > 1){
        	 unionStream = jssc.union(mapStreams.get(0), mapStreams.subList(1, mapStreams.size()));
        }else{
        	 unionStream = mapStreams.get(0);
        }
        
        //reduce计算
        JavaPairDStream<String, CpcDisplayValue> reduceStream = mr.reducePair(unionStream);
        
        //输出结果 写入redis
        mr.foreachRDD(reduceStream);
        
        jssc.start(); //上下文开始
		jssc.awaitTermination(); 
	}

}
